package com.chenwb.concurrency.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReenterLock implements Runnable {
	ReentrantLock reenteantLock = new ReentrantLock();
	static int i = 0;

	/**
	 * 执行
	 */
	@Override
	public void run() {
		for (int j = 0; j < 100000; j++) {
			reenteantLock.lock();
			try {
				i++;
			} finally {
				reenteantLock.unlock();
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		//注意，这里不要创建两个不同实例，因为此时的reenteantLock是两个,如果要这样写，那么重入锁应为static，为类拥有，那么也是线程安全的
/*		Thread t1 = new Thread(new ReenterLock());
		Thread t2 = new Thread(new ReenterLock());*/
		ReenterLock thread = new ReenterLock();
		Thread t1 = new Thread(thread);
		Thread t2 = new Thread(thread);
		t1.start();t2.start();
		t1.join();t2.join();
		System.out.println(i);
	}
}
